<template>
  <el-dialog
    v-model="visible"
    :title="$t('order.refundProcessing')"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    width="80%"
    class="dialog-add-or-update"
    @close="onDialogClose"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="100px"
      @submit.prevent
    >
      <div class="mod-order-refundOrderInfo">
        <div class="content">
          <div class="order-number">
            <div class="num-cont">
              <el-form-item :label="$t('order.refundId') + ':'">
                <span class="text">{{ dataForm.refundSn }}</span>
              </el-form-item>
              <el-form-item>
                <div
                  v-if="dataForm.applyType === 1"
                  style="width:100%"
                >
                  <el-steps
                    :active="onlyRefundStepsStatus"
                    align-center
                    :process-status="onlyRefundProcessStatus"
                  >
                    <el-step
                      :title="$t('order.buyer') + ' ' + $t('order.requestARefund')"
                    />
                    <el-step :title="$t('admin.merAgreeRefund')" />
                    <el-step :title="$t('order.refundsuccessfully')" />
                  </el-steps>
                </div>
                <div
                  v-else
                  style="width:100%"
                >
                  <el-steps
                    :active="stepsStatus"
                    align-center
                    :process-status="dataForm.returnMoneySts === -1 ? 'error' : 'wait'"
                  >
                    <el-step
                      :title="$t('order.buyer') + ' ' + $t('order.requestARefundT')"
                    />
                    <el-step
                      :title="$t('order.merchant') + ' ' + $t('order.agreeToReturnAndRefund')"
                    />
                    <el-step :title="$t('order.shipped')" />
                    <el-step
                      :title="$t('order.merchant') + ' ' + $t('order.successfulProcessing')"
                    />
                    <el-step :title="$t('order.refundsuccessfully')" />
                  </el-steps>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="order-state">
            <div class="state-cont">
              <div class="state-title">
                <el-form-item :label="$t('order.returnType') + ':'">
                  <el-tag
                    v-if="dataForm.refundType === 1"
                    type="warning"
                  >
                    {{
                      $t('order.wholeOrderRefund')
                    }}
                  </el-tag>
                  <el-tag
                    v-if="dataForm.refundType === 2"
                    type="warning"
                  >
                    {{
                      $t('order.singleItemRefund')
                    }}
                  </el-tag>
                </el-form-item>
                <el-form-item :label="$t('order.applicationType') + ':'">
                  <el-tag
                    v-if="dataForm.applyType === 1"
                    type="warning"
                  >
                    {{
                      $t('order.onlyRefund')
                    }}
                  </el-tag>
                  <el-tag
                    v-if="dataForm.applyType === 2"
                    type="warning"
                  >
                    {{
                      $t('order.refundAndMoney')
                    }}
                  </el-tag>
                </el-form-item>
                <el-form-item v-if="dataForm.decisionTime && !dataForm.refundTime">
                  <div>
                    {{ $t('order.wait') }}
                    {{
                      [
                        $t('order.pointsPayment'),
                        $t('order.wecProPay'),
                        $t('order.alipayPCPayment'),
                        $t('order.wechatScanCodePayment'),
                        $t('order.wechatH5Payment'),
                        $t('order.weclAccountPay'),
                        $t('order.alipayH5Payment'),
                        $t('order.alipayAPPPayment'),
                        $t('order.wechatAPPPayment'),
                        $t('order.balancePayment'),
                        $t('order.payPalPayment')
                      ][dataForm.payType]
                    }}
                    {{ $t('order.refund') }}
                  </div>
                </el-form-item>
              </div>

              <div class="order-state">
                <div class="state-cont">
                  <div class="order-info">
                    <div class="order-details">
                      <div class="detail-title">
                        <img
                          src="~@/assets/img/car.png"
                          alt
                        >
                        <span class="prompt">{{ $t('order.returnDetails') }}</span>
                      </div>
                      <div class="detail-cont">
                        <div class="detail01">
                          <div class="text-width">
                            <el-form-item
                              :label="$t('order.number') + ':'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span>{{ dataForm.orderNumber }}</span>
                            </el-form-item>
                            <el-form-item
                              :label="$t('order.actualAmount') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span>
                                {{ dataForm.totalActualAmount + $t('admin.dollar') }}
                                <span v-if="dataForm.refundScore">{{ `+ ${dataForm.refundScore + $t('order.integral')}` }}
                                </span>
                              </span>
                            </el-form-item>
                            <el-form-item
                              :label="$t('order.refundAmount') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <!-- <span>{{dataForm.refundAmount}}</span> -->
                              <span>
                                {{ dataForm.refundAmount + $t('admin.dollar') }}
                                <span v-if="dataForm.refundScore">{{ `+ ${dataForm.refundScore + $t('order.integral')}` }}
                                </span>
                              </span>
                            </el-form-item>
                            <el-form-item
                              :label="$t('order.applicationTime') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span>{{ dataForm.applyTime }}</span>
                            </el-form-item>
                            <el-form-item
                              :label="$t('order.reasonForReturn') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span>{{ dataForm.buyerReason }}</span>
                            </el-form-item>
                            <el-form-item
                              :label="$t('order.refundInstructions') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span style="word-break: break-word">{{ dataForm.buyerDesc }}</span>
                            </el-form-item>
                            <el-form-item
                              v-if="dataForm.buyerMobile"
                              :label="$t('publics.mobilePhone') + '：'"
                              :class="[$t('language') === '简体中文' ? '' : 'refund-label-en']"
                            >
                              <span style="word-break: break-word">{{ dataForm.buyerMobile }}</span>
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- 退款凭证 -->
                    <div class="buyers">
                      <div class="detail-title">
                        {{ $t('order.returnCertificate') }}
                      </div>
                      <div class="buyers-info">
                        <div class="img-up">
                          <imgs-upload
                            v-model="dataForm.photoFiles"
                            :disabled="true"
                            :modal="true"
                            :prompt="false"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- 物流信息 -->
                  <div
                    v-if="
                      dataForm.refundDelivery &&
                        (dataForm.refundDelivery.deyNu || dataForm.refundDelivery.imgs)
                    "
                    class="order-info"
                  >
                    <div class="order-details">
                      <div class="detail-title">
                        <span class="prompt">{{ $t('order.logisticsDetails') }}</span>
                      </div>
                      <div class="detail-cont">
                        <div class="detail01">
                          <div class="text-width">
                            <div
                              v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyName"
                              class="text-width-item"
                            >
                              <span class="title">{{ $t('order.logisticsName') }}：</span>
                              <span class="text">{{ dataForm.refundDelivery.deyName }}</span>
                            </div>
                            <div
                              v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyNu"
                              class="text-width-item"
                            >
                              <span class="title">{{ $t('order.trackingNumber') }}：</span>
                              <span class="text">{{ dataForm.refundDelivery.deyNu }}</span>
                            </div>
                            <div
                              v-if="
                                dataForm.refundDelivery && dataForm.refundDelivery.senderRemarks
                              "
                              class="text-width-item"
                            >
                              <span class="title">{{ $t('order.compradorMsg') }}：</span>
                              <span class="text">{{
                                dataForm.refundDelivery.senderRemarks
                              }}</span>
                            </div>
                            <div
                              v-if="
                                dataForm.refundDelivery && dataForm.refundDelivery.senderMobile
                              "
                              class="text-width-item"
                            >
                              <span class="title">{{ $t('order.buyerPhone') }}：</span>
                              <span>{{ dataForm.refundDelivery.senderMobile }}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="refund-detail-voucher">
                        <div class="detail-title">
                          <img
                            width="18px"
                            height="18px"
                            src="~@/assets/img/car.png"
                            alt
                            style="margin-right: 15px;margin-bottom: 18px;"
                          >
                          <el-form-item
                            :label="$t('order.logisticsCertificate')"
                          >
                            <div class="buyers-info">
                              <div class="detail02" />
                            </div>
                          </el-form-item>
                        </div>
                        <div
                          class="buyers-info logistics-voucher-wrap"
                        >
                          <imgs-upload
                            v-model="logisticsVoucher"
                            :disabled="true"
                            :modal="true"
                            :prompt="false"
                          />
                        </div>
                      </div>
                    </div>
                    <!-- 物流信息 -->
                    <div class="buyers">
                      <div
                        v-if="deliveryDto"
                        class="detail-title"
                      >
                        <!-- 退款物流信息 -->
                        <span>{{ $t('order.logisticsStatus') }}：</span>
                        <span
                          v-if="deliveryDto.state === 0"
                          class="l-state"
                        >{{
                          $t('order.noRecord')
                        }}</span>
                        <span
                          v-if="deliveryDto.state === 1"
                          class="l-state"
                        >{{
                          $t('order.collected')
                        }}</span>
                        <span
                          v-if="deliveryDto.state === 2"
                          class="l-state"
                        >{{
                          $t('order.delivering')
                        }}</span>
                        <span
                          v-if="deliveryDto.state === 3"
                          class="l-state"
                        >{{
                          $t('order.haveBeenReceived')
                        }}</span>
                        <span
                          v-if="deliveryDto.state === 4"
                          class="l-state"
                        >{{
                          $t('order.problemPiece')
                        }}</span>
                        <span
                          v-if="deliveryDto.state === 201"
                          class="l-state"
                        >{{
                          $t('order.reachTheDestinationCity')
                        }}</span>
                      </div>
                      <div
                        v-if="deliveryDto"
                        class="logistics-box"
                      >
                        <!-- 退款时间 -->
                        <div
                          v-if="dataForm.returnMoneySts === 5 && dataForm.refundTime !== null"
                          class="item"
                        >
                          <div class="time">
                            {{ dataForm.refundTime }}
                          </div>
                          <div class="text">
                            {{ $t('refund.refundMoney') }}
                          </div>
                        </div>
                        <!-- 收货时间 -->
                        <div
                          v-if="dataForm.returnMoneySts === 5 && dataForm.receiveTime !== null"
                          class="item"
                        >
                          <div class="time">
                            {{ dataForm.receiveTime }}
                          </div>
                          <div class="text">
                            {{ $t('refund.receivedGoods') }}
                          </div>
                        </div>
                        <div
                          v-for="(trace, index) in deliveryDto.traces"
                          :key="index"
                          class="item"
                        >
                          <div class="time">
                            {{ trace.acceptTime }}
                          </div>
                          <div class="text">
                            {{ trace.acceptStation }}
                          </div>
                        </div>
                        <div
                          v-if="deliveryDto.traces && deliveryDto.traces.length < 1"
                          class="item"
                        >
                          {{ $t('order.noLogisticsInformation') }}
                        </div>
                        <!-- 发货时间 -->
                        <div
                          v-if="dataForm.returnMoneySts >= 3 && dataForm.shipTime !== null"
                          class="item"
                        >
                          <div class="time">
                            {{ dataForm.shipTime }}
                          </div>
                          <div class="text">
                            {{ $t('refund.buyerHasShipped') }}
                          </div>
                        </div>
                        <!-- 同意退款时间 -->
                        <div
                          v-if="dataForm.returnMoneySts >= 2 && dataForm.decisionTime !== null"
                          class="item"
                        >
                          <div class="time">
                            {{ dataForm.decisionTime }}
                          </div>
                          <div class="text">
                            {{ $t('refund.merchantHasAgree') }}
                          </div>
                        </div>
                        <!-- 申请时间 -->
                        <div
                          v-if="dataForm.returnMoneySts >= 1"
                          :class="['item', dataForm.returnMoneySts >= 1 ? 'left-line' : '']"
                        >
                          <div class="time">
                            {{ dataForm.applyTime }}
                          </div>
                          <div class="text">
                            {{ $t('refund.buyerApply') }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="main-container">
                <div class="table-con prod-table item-list">
                  <el-table
                    :data="dataForm.orderItems"
                    header-cell-class-name="table-header"
                    style="width: 100%"
                  >
                    <el-table-column
                      label=""
                      width="100"
                      align="center"
                    >
                      <template #default="scope">
                        <div class="table-cell-con">
                          <div class="table-cell-image">
                            <ImgShow :src="scope.row.pic" />
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      prop="prodName"
                      :label="$t('order.refundGoods')"
                    >
                      <template #default="scope">
                        <div class="table-cell-con">
                          <span class="table-cell-text">{{ scope.row.prodName }}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="price"
                      :label="$t('order.unitPrice')"
                      width="180"
                      align="center"
                    >
                      <template #default="scope">
                        <span>{{ scope.row.price }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="count"
                      :label="$t('order.quantity')"
                      width="180"
                      align="center"
                    >
                      <template #default="scope">
                        <span v-if="dataForm.refundType === 1">{{ scope.row.prodCount }}</span>
                        <span v-if="dataForm.refundType === 2">{{ dataForm.goodsNum }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="productTotalAmount"
                      :label="$t('order.prodTotalPrice')"
                      width="180"
                      align="center"
                    >
                      <template #default="scope">
                        <span v-if="dataForm.refundType === 1">{{
                          scope.row.productTotalAmount
                        }}</span>
                        <span v-if="dataForm.refundType === 2">{{
                          bigProductTotalAmount(scope.row.price, dataForm.goodsNum)
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="actualTotal"
                      :label="$t('order.actualAmount')"
                      width="180"
                      align="center"
                    >
                      <template #default="scope">
                        <span v-if="dataForm.refundType === 1">{{ scope.row.actualTotal }}</span>
                        <span v-if="dataForm.refundType === 2">{{
                          bigActualTotal(scope.row.actualTotal, scope.row.prodCount)
                        }}</span>
                        <el-tag
                          v-if="scope.row.shareReduce > 0"
                          type="danger"
                          effect="dark"
                        >
                          {{ $t('order.discount') }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="productTotalAmount"
                      :label="$t('order.returnAmount')"
                      width="180"
                      align="center"
                    >
                      <span>{{ dataForm.refundAmount + $t('admin.dollar') }}
                        <span v-if="dataForm.refundScore">{{
                          ` + ${dataForm.refundScore + $t('order.integral')}`
                        }}</span>
                      </span>
                    </el-table-column>
                  </el-table>
                </div>
              </div>

              <div
                v-if="dataForm.returnMoneySts === 1"
                class="sellerRemark"
              >
                <el-row>
                  <el-col :span="2">
                    <div>{{ $t('order.applyForApproval') }}:</div>
                  </el-col>
                  <el-col :span="22">
                    <div>
                      <el-radio-group v-model="isAgreeRefund">
                        <el-radio :label="2">
                          {{
                            dataForm.applyType === 1 ? $t('order.agreeToRefundA') : $t('order.agree')
                          }}
                        </el-radio>
                        <el-radio :label="3">
                          {{ $t('order.disagree') }}
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </el-col>
                </el-row>
              </div>

              <div
                v-if="dataForm.applyType === 2 && isAgreeRefund === 2"
                class="sellerRemark"
              >
                <el-row>
                  <el-col :span="2">
                    <div
                      v-if="
                        (dataForm.refundDelivery.receiverAddr &&
                          (dataForm.returnMoneySts === 5 || dataForm.returnMoneySts === -1)) ||
                          (dataForm.returnMoneySts !== 5 && dataForm.returnMoneySts !== -1)
                      "
                    >
                      {{ $t('publics.deliveryAddr') }}：
                    </div>
                  </el-col>
                  <el-col :span="22">
                    <div v-if="dataForm.returnMoneySts === 1">
                      <el-select
                        ref="dataSelectRef"
                        v-model="dataForm.refundAddrId"
                        :class="[
                          'deliveryAddrName',
                          $t('language') === '简体中文' ? '' : 'deliveryAddrNameEn'
                        ]"
                        :placeholder="$t('tip.select')"
                        @change="$forceUpdate()"
                      >
                        <el-option
                          v-for="item in addrList"
                          :key="item.refundAddrId"
                          style="max-width: 800px"
                          :label="
                            item.receiverName +
                              '，' +
                              item.receiverMobile +
                              '，' +
                              item.province +
                              item.city +
                              item.area +
                              item.addr
                          "
                          :value="item.refundAddrId"
                        />
                      </el-select>
                      <!--            新建/刷新-->
                      <el-button
                        type="text"
                        @click="refreshChange"
                      >
                        {{
                          $t('admin.refresh')
                        }}
                      </el-button>
                      <el-divider direction="vertical" />
                      <el-button
                        type="text"
                        @click.stop="onAddOrUpdate()"
                      >
                        {{
                          $t('admin.newConstruction')
                        }}
                      </el-button>
                    </div>
                    <!-- 弹窗, 新建 -->
                    <div v-if="dataForm.refundDelivery.receiverAddr">
                      {{
                        dataForm.refundDelivery.receiverName +
                          '，' +
                          dataForm.refundDelivery.receiverMobile +
                          '，' +
                          dataForm.refundDelivery.receiverAddr
                      }}
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div
                v-if="dataForm.shipTime && !dataForm.cancelTime && !dataForm.rejectTime"
                class="sellerRemark"
              >
                <el-row>
                  <el-col :span="2">
                    <div>{{ $t('order.returnStatus') }}:</div>
                  </el-col>
                  <el-col :span="22">
                    <div>
                      <el-radio-group
                        v-model="isReceiver"
                        :disabled="dataForm.returnMoneySts !== 3"
                      >
                        <!-- <el-radio :label="1">待审核</el-radio> -->
                        <el-radio :label="1">
                          {{ $t('order.received') }}
                        </el-radio>
                        <el-radio :label="0">
                          {{ $t('order.unreceived') }}
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </el-col>
                </el-row>
              </div>

              <div
                v-if="dataForm.shipTime && !dataForm.cancelTime && !dataForm.rejectTime"
                class="sellerRemark"
              >
                <el-row>
                  <el-col :span="2">
                    <div>{{ $t('order.returnRequest') }}:</div>
                  </el-col>
                  <el-col :span="22">
                    <div>
                      <el-radio-group
                        v-model="isAgreeRefund"
                        :disabled="dataForm.returnMoneySts !== 3"
                      >
                        <el-radio :label="2">
                          {{ $t('order.agreeToRefundA') }}
                        </el-radio>
                        <el-radio :label="3">
                          {{ $t('order.refusalToRefund') }}
                        </el-radio>
                      </el-radio-group>
                    </div>
                  </el-col>
                </el-row>
              </div>

              <div
                v-if="isAgreeRefund === 3"
                class="sellerRemark"
              >
                <el-row>
                  <el-col :span="2">
                    <div><span class="red">*</span>{{ $t('order.denialReason') }}：</div>
                  </el-col>
                  <el-col :span="22">
                    <div>
                      <el-input
                        v-model="dataForm.rejectMessage"
                        type="textarea"
                        :rows="4"
                        maxlength="250"
                        show-word-limit
                        :placeholder="$t('order.denialReason')"
                        @blur="dataForm.rejectMessage = onHandleInputSpaces(dataForm.rejectMessage)"
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div class="sellerRemark">
                <el-row>
                  <el-col :span="2">
                    <div>{{ $t('order.merchantNotes') }}:</div>
                  </el-col>
                  <el-col :span="22">
                    <div>
                      <el-input
                        v-model="dataForm.sellerMsg"
                        type="textarea"
                        :disabled="dataForm.returnMoneySts !== 1"
                        :rows="4"
                        maxlength="250"
                        show-word-limit
                        :placeholder="$t('order.merchantNotes')"
                        @blur="dataForm.sellerMsg = onHandleInputSpaces(dataForm.sellerMsg)"
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>

              <div style="float: right">
                <el-form-item>
                  <el-row>
                    <!-- 仅退款的时候进行的处理操作 -->
                    <div
                      v-if="dataForm.returnMoneySts === 1"
                      class="default-btn primary-btn"
                      @click="onCheckHandel()"
                    >
                      {{ $t('order.confirmTreatment') }}
                    </div>
                    <!-- 退货退款的时候进行的处理操作 -->
                    <div
                      v-if="dataForm.returnMoneySts === 3"
                      class="default-btn primary-btn"
                      @click="onReturnMoneyHandle()"
                    >
                      {{ $t('order.confirmTreatment') }}
                    </div>
                  </el-row>
                </el-form-item>
              </div>
            </div>
          </div>

          <div class="order-log">
            <div class="log-title">
              <span>{{ $t('order.refundLog') }}</span>
            </div>
            <div class="log-cont">
              <el-form-item
                v-if="dataForm.applyTime"
                label-width="10px"
              >
                <span>{{ dataForm.applyTime }} {{ $t('order.submitARefundRequestWa') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.applyType === 2 && dataForm.handelTime"
                label-width="10px"
              >
                <span>{{ dataForm.handelTime }} {{ $t('order.merchantHasProcessedWaBuy') }}</span>
              </el-form-item>

              <el-form-item
                v-if="dataForm.applyType === 1 && dataForm.handelTime"
                label-width="10px"
              >
                <span>{{ dataForm.handelTime }} {{ $t('order.merchantHasProcessedWaSh') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.shipTime"
                label-width="10px"
              >
                <span>{{ dataForm.shipTime }} {{ $t('order.buyerShipmentWaPro') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.receiveTime"
                label-width="10px"
              >
                <span>{{ dataForm.receiveTime }} {{ $t('order.merchantHasReceivedWaShGr') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.decisionTime"
                label-width="10px"
              >
                <span>{{ dataForm.decisionTime }} {{ $t('order.agreeToRefund') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.refundTime"
                label-width="10px"
              >
                <span>{{ dataForm.refundTime }} {{ $t('order.refundsuccessfully') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.returnMoneySts === -1 && dataForm.cancelTime"
                label-width="10px"
              >
                <span>{{ dataForm.cancelTime }} {{ $t('order.refundClosed') }}
                  {{ $t('order.buyerHasWithdrawn') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.returnMoneySts === -1 && dataForm.rejectTime"
                label-width="10px"
              >
                <span>{{ dataForm.rejectTime }} {{ $t('order.refundFailed') }}
                  {{ $t('order.merchantRejected') }}</span>
              </el-form-item>
              <el-form-item
                v-if="dataForm.handelTime && dataForm.returnMoneySts === -1"
                label-width="10px"
              >
                <span>{{ dataForm.updateTime }} {{ $t('order.refundClosed') }}</span>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetRefundAddrList"
    />
  </el-dialog>
</template>

<script setup>
import AddOrUpdate from '@/views/modules/shop/refund-addr/add-or-update.vue'
import Big from 'big.js'
import { ElMessageBox, ElMessage } from 'element-plus'
const emit = defineEmits([
  'refreshDataList'
])

const visible = ref(false)
const addOrUpdateVisible = ref(false)
const devyVisible = ref(false)

watch(visible, () => {
  if (visible.value) {
    devyVisible.value = false
    addOrUpdateVisible.value = false
  }
})
const dataForm = ref({})

const onlyRefundStepsStatus = computed(() => {
  let index = 0
  if (dataForm.value.handelTime) {
    index++
  }
  if (dataForm.value.cancelTime || dataForm.value.refundTime) {
    index += 2
  }
  return index
})
const onlyRefundProcessStatus = computed(() => {
  switch (dataForm.value.returnMoneySts) {
    case 1:
    case 2:
      return 'finish'
    case 5:
      return 'success'
    default:
      return 'error'
  }
})
const stepsStatus = computed(() => {
  let index = 1
  if (dataForm.value.handelTime) {
    index++
  }
  if (dataForm.value.shipTime) {
    index++
  }
  if (
    (dataForm.value.shipTime && dataForm.value.rejectTime) ||
    dataForm.value.receiveTime ||
    dataForm.value.returnMoneySts === 5
  ) {
    index++
  }
  // 退款成功的情况下进度条也要加2
  if (dataForm.value.returnMoneySts === 5) {
    index += 2
  }
  return index
})
const refundphotos = ref([])
const refundDeliveryPhotos = ref([])
const isAgreeRefund = ref(2)
const deliveryDto = ref(null)
const isReceiver = ref(0)
const logisticsVoucher = ref('') // 物流凭证
const dataFormRef = ref(null)

const init = id => {
  dataForm.value.refundId = id || 0
  isReceiver.value = 0
  visible.value = true
  nextTick(() => {
    dataFormRef.value.resetFields()
  })
  refundphotos.value = []
  refundDeliveryPhotos.value = []
  isAgreeRefund.value = 2
  if (dataForm.value.refundId) {
    http({
      url: http.adornUrl(`/order/refund/info/${dataForm.value.refundId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      deliveryDto.value = dataForm.value.deliveryDto
      if (dataForm.value.isReceiver) {
        isReceiver.value = 1
      } else {
        isReceiver.value = 0
      }
      if (dataForm.value.photoFiles) {
        refundphotos.value = dataForm.value.photoFiles.split(',')
      }
      if (dataForm.value.refundDelivery && dataForm.value.refundDelivery.imgs) {
        refundDeliveryPhotos.value = dataForm.value.refundDelivery.imgs.split(',')
        nextTick(() => {
          logisticsVoucher.value = dataForm.value.refundDelivery.imgs
        })
      }
      if (dataForm.value.orderItems) {
        dataForm.value.totalActualAmount = 0
        dataForm.value.orderItems.forEach(item => {
          dataForm.value.totalActualAmount = new Big(dataForm.value.totalActualAmount).plus(
            item.actualTotal
          )
        })
      }
      onGetRefundAddrList()
      onGetIsInvoiceUpload(data.orderNumber)
    })
  }
}
const onGetIsInvoiceUpload = orderNumber => {
  http({
    url: http.adornUrl('/m/orderInvoice/is_upload'),
    method: 'get',
    params: {
      orderNumber
    }
  }).then(({ data }) => {
    isUploadInvoice = data
  })
}
// 新增
const addOrUpdateRef = ref(null)
const onAddOrUpdate = () => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init()
  })
}
// 刷新
const refreshChange = () => {
  onGetRefundAddrList()
}
// 表单提交
/**
 * 加载收货地址模板
 */
const addrList = ref([])
const refundAddr = ref('')

const onGetRefundAddrList = () => {
  http({
    url: http.adornUrl('/shop/refundAddr/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    addrList.value = data
    addrList.value.forEach(row => {
      if (row.defaultAddr === 1) {
        dataForm.value.refundAddrId = row.refundAddrId
      }
    })
    if (dataForm.value.refundAddrId) {
      const index = addrList.value.findIndex(
        item => item.refundAddrId === dataForm.value.refundAddrId
      )
      if (index || index === 0) {
        const refAddr = addrList.value[index]
        refundAddr.value = refAddr.province + refAddr.city + refAddr.area + refAddr.addr
      }
    }
  })
}

/**
 * 输入框纯空格处理
 */
const onHandleInputSpaces = value => {
  if (!value) {
    return
  }
  if (!value.trim()) {
    return value.trim()
  } else {
    return value
  }
}

/**
 * 仅退款的时候，进行的退款处理操作
 * 提交处理
 */
let isUploadInvoice = false
const onCheckHandel = () => {
  if (isAgreeRefund.value === 2) {
    if (isUploadInvoice) {
      ElMessageBox.confirm($t('order.refundTip'), $t('remindPop.remind'), {
        confirmButtonText: $t('remindPop.confirm'),
        cancelButtonText: $t('remindPop.cancel'),
        type: 'warning'
      }).then(() => {
        if (
          dataForm.value.refundType === 2 &&
            dataForm.value.applyType === 1 &&
            dataForm.value.status === 2
        ) {
          onCheckIsLastOrderItem(onHandelReturnMoney)
          return
        }
        onHandelReturnMoney()
      })
      return
    } else {
      if (
        dataForm.value.refundType === 2 &&
        dataForm.value.applyType === 1 &&
        dataForm.value.status === 2
      ) {
        onCheckIsLastOrderItem(onHandelReturnMoney)
        return
      }
      onHandelReturnMoney()
    }
  }
  onHandelReturnMoney()
}

/**
 * 是否为最后一个退款项
 */
const onCheckIsLastOrderItem = fn => {
  http({
    url: http.adornUrl('/order/refund/isLastRefund'),
    method: 'get',
    params: http.adornParams({
      refundSn: dataForm.value.refundSn
    })
  }).then(({ data }) => {
    if (data) {
      if (dataForm.value.freightAmount.toFixed(2) + '' !== '0.00') {
        ElMessageBox.confirm(
          $t('order.lastProdRefundTip').replace(
            '[d]',
            dataForm.value.freightAmount.toFixed(2) + ' '
          ),
          $t('resource.tips'),
          {
            confirmButtonText: $t('resource.confirm'),
            cancelButtonText: $t('resource.cancel'),
            type: 'warning'
          }
        ).then(() => {
          fn()
        })
      } else {
        fn()
      }
    } else {
      fn()
    }
  })
}
const isProcessing = ref(false) // 是否正在处理订单

const onHandelReturnMoney = () => {
  const tempRefundAddrId = isAgreeRefund.value === 2 ? dataForm.value.refundAddrId : undefined
  if (isProcessing.value) {
    return
  }
  if (isAgreeRefund.value === 3) {
    if (dataForm.value.rejectMessage == null || dataForm.value.rejectMessage === '') {
      ElMessage.error($t('order.denialReason') + $t('order.cannotEmpty'))
      return
    }
  }
  isProcessing.value = true
  http({
    url: http.adornUrl('/order/refund/process'),
    method: 'put',
    data: http.adornData({
      refundId: dataForm.value.refundId,
      refundSts: isAgreeRefund.value,
      refundSn: dataForm.value.refundSn,
      rejectMessage: dataForm.value.rejectMessage,
      sellerMsg: dataForm.value.sellerMsg,
      refundAddrId: tempRefundAddrId
    })
  }).then(() => {
    emit('refreshDataList')
    visible.value = false
    isProcessing.value = false
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {}
    })
  }).catch(() => {
    isProcessing.value = false
  })
}
/**
 * 确定退款
 */
const onReturnMoneyHandle = () => {
  if (isProcessing.value) {
    return
  }
  if (isAgreeRefund.value === 3) {
    if (dataForm.value.rejectMessage == null || dataForm.value.rejectMessage === '') {
      ElMessage.error($t('order.denialReason') + $t('order.cannotEmpty'))
      return
    }
  }
  isProcessing.value = true
  http({
    url: http.adornUrl('/order/refund/returnMoney'),
    method: 'put',
    data: http.adornData({
      refundId: dataForm.value.refundId,
      refundSts: isAgreeRefund.value,
      refundSn: dataForm.value.refundSn,
      rejectMessage: dataForm.value.rejectMessage,
      sellerMsg: dataForm.value.sellerMsg,
      isReceiver: isReceiver.value
    })
  }).then(() => {
    isProcessing.value = false
    emit('refreshDataList')
    visible.value = false
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {}
    })
  }).catch(() => {
    isProcessing.value = false
  })
}

// 精度运算-乘法
const bigProductTotalAmount = (a, b) => {
  return new Big(a).times(b)
}
// 精度运算-除法
const bigActualTotal = (a, b) => {
  if (a == null) {
    return ''
  }
  return new Big(a).div(b).times(dataForm.value.goodsNum).toFixed(2)
}
const dataSelectRef = ref(null)
const onDialogClose = () => {
  dataSelectRef.value?.blur()
}
defineExpose({ init })
</script>

<style lang="scss" scoped>
@use './add-or-update.scss';
</style>
